package com.pzb.web.controller.wxpay;

import com.pzb.common.core.controller.BaseController;
import com.pzb.common.core.domain.AjaxResult;

import com.pzb.wxpay.service.IWxPayService;
import com.pzb.wxpay.util.PayUtil;
import com.pzb.wxpay.util.WechatConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wxPay")
public class WxPayController extends BaseController {

    @Autowired
    private IWxPayService wxPayService;

    //这里是支付回调接口，微信支付成功后会自动调用
    @PostMapping(value = "/wxNotify")
    public void wxNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {

        String resXml = wxPayService.wxNotify(request);
        BufferedOutputStream out = new BufferedOutputStream(
                response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();
    }



    /**
     * 统一下单
     */
    @GetMapping("/paytest")
    public AjaxResult paytest(HttpServletRequest request) throws Exception {
        //获取客户端的ip地址
        String spbillCreateIp = "192.168.0.110";
        //生成的随机字符串
        String nonce_str = PayUtil.getRandomStringByLength(32);
        //商品名称
        //todo
        String body = "测试下单";
        //获取客户端的ip地址
        BigDecimal b = new BigDecimal(100.00);
        int price = new BigDecimal("0.10").multiply(b).intValue();

        //组装参数，用户生成统一下单接口的签名
        System.err.println("----------下单接口签名-------");
        Map<String, String> packageParams = new HashMap<>();
        packageParams.put("appid", "wx4f91df89416893c2");
        packageParams.put("mch_id", "1621925064");
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("body", body);
        packageParams.put("out_trade_no", "20220221164927783001");//商户订单号,自己的订单ID
        packageParams.put("total_fee", price + "");//支付金额，这边需要转成字符串类型，否则后面的签名会失败
        packageParams.put("spbill_create_ip", spbillCreateIp);
        packageParams.put("notify_url", "https://www.bluesharksys.com/uni-api/wxPay/wxNotify");//支付成功后的回调地址
        packageParams.put("trade_type", WechatConfig.TRADETYPE);//支付方式
        packageParams.put("openid", "oyXYZ5Qngq2Q_YM1IeNaJimGNKf4");//用户的openID，自己获取
        String prestr = PayUtil.createLinkString(packageParams); // 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
        System.err.println("----------prestr:" + prestr);
        System.err.println("----------调用统一下单接口-------");
        //MD5运算生成签名，这里是第一次签名，用于调用统一下单接口
        String mysign = PayUtil.sign(prestr, WechatConfig.key, "utf-8").toUpperCase();
        System.err.println("----------mysign:" + mysign);
        //拼接统一下单接口使用的xml数据，要将上一步生成的签名一起拼接进去
        String xml = "<xml>" + "<appid>wx4f91df89416893c2</appid>"
                + "<body><![CDATA[" + body + "]]></body>"
                + "<mch_id>1621925064</mch_id>"
                + "<nonce_str>" + nonce_str + "</nonce_str>"
                + "<notify_url>https://www.bluesharksys.com/uni-api/wxPay/wxNotify</notify_url>"
                + "<openid>oyXYZ5Qngq2Q_YM1IeNaJimGNKf4</openid>"
                + "<out_trade_no>20220221164927783001</out_trade_no>"
                + "<spbill_create_ip>" + spbillCreateIp + "</spbill_create_ip>"
                + "<total_fee>" + price + "</total_fee>"//支付的金额，单位：分
                + "<trade_type>" + WechatConfig.TRADETYPE + "</trade_type>"
                + "<sign>" + mysign + "</sign>"
                + "</xml>";


        //调用统一下单接口，并接受返回的结果
        String result = PayUtil.httpRequest(WechatConfig.pay_url, "POST", xml);

        System.err.println("----------result:" + result);

        // 将解析结果存储在HashMap中
        Map map = PayUtil.doXMLParse(result);

        return AjaxResult.success(map);
    }
}
